 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=131 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Arrays as String 
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='toString,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Arrays as String </div>

<div class='main-body'>
 
<br>Logging the contents of a&nbsp;<tt>Collection</tt> is simple, since&nbsp;<tt><a href="http://java.sun.com/javase/6/docs/api/java/util/AbstractCollection.html#toString()">AbstractCollection.toString</tt></a>
is always available. For an array, however, the default <tt>toString</tt> method  
is not very informative, and does not include the array contents.

<P>To provide more useful representations of arrays, various <tt>toString</tt> methods 
(and the <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#deepToString(java.lang.Object[])"><tt>deepToString</tt></a> 
method)
were added to the
<a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html"><tt>Arrays</tt></a> class in JDK 1.5. 
Those methods can be used when available, as in :
<PRE>
Arrays.<a href='http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#toString(java.lang.Object[])'>toString</a>(myArray); 
Arrays.<a href='http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#deepToString(java.lang.Object[])'>deepToString</a>(myObjectArray); //recursive
</PRE>
<P>If you need an alternative, you can simply convert the array to a collection, as in 
<PRE>
Arrays.<a href='http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)'>asList</a>(myArray).toString();
</PRE>

<p>Finally, here is a third option, using a utility class which :
<ul>
<li>uses a slightly different style from that used in <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html"><tt>Arrays</tt></a>
<li>works with versions of the JDK prior to 1.5. 
<li>returns text in the same format as <a href="http://java.sun.com/javase/6/docs/api/java/util/AbstractCollection.html#toString()"><tt>AbstractCollection.toString</tt></a>
<li>handles arrays of all primitive types, and arrays of <tt>Object</tt>s as well
<li>handles arrays of arrays by using recursion
</ul>

<br>
<PRE>

<span class='keyword'>package</span> myapp.business;

<span class='keyword'>import</span> java.lang.reflect.Array;

<span class='comment'>/**
* Convenience method for producing a simple textual
* representation of an array.
*
* &lt;P&gt;The format of the returned &lt;code&gt;String&lt;/code&gt; is the same as
* &lt;code&gt;AbstractCollection.toString&lt;/code&gt;:
* &lt;ul&gt;
* &lt;li&gt;non-empty array: [blah, blah]
* &lt;li&gt;empty array: []
* &lt;li&gt;null array: null
* &lt;/ul&gt;
*
* @author Jerome Lacoste
* @author www.javapractices.com
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ArrayToString {

  <span class='comment'>/**
  * &lt;code&gt;aArray&lt;/code&gt; is a possibly-null array whose elements are
  * primitives or objects; arrays of arrays are also valid, in which case
  * &lt;code&gt;aArray&lt;/code&gt; is rendered in a nested, recursive fashion.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> String get(Object aArray){
    <span class='keyword'>if</span> ( aArray == <span class='keyword'>null</span> ) <span class='keyword'>return</span> fNULL;
    checkObjectIsArray(aArray);

    StringBuilder result = <span class='keyword'>new</span> StringBuilder( fSTART_CHAR );
    <span class='keyword'>int</span> length = Array.getLength(aArray);
    <span class='keyword'>for</span> ( <span class='keyword'>int</span> idx = <span class='literal'>0</span> ; idx &lt; length ; ++idx ) {
      Object item = Array.get(aArray, idx);
      <span class='keyword'>if</span> ( isNonNullArray(item) ){
        <span class='comment'>//recursive call!
</span>        result.append( get(item) );
      }
      <span class='keyword'>else</span>{
        result.append( item );
      }
      <span class='keyword'>if</span> ( ! isLastItem(idx, length) ) {
        result.append(fSEPARATOR);
      }
    }
    result.append(fEND_CHAR);
    <span class='keyword'>return</span> result.toString();
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fSTART_CHAR = <span class='literal'>"["</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fEND_CHAR = <span class='literal'>"]"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fSEPARATOR = <span class='literal'>", "</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fNULL = <span class='literal'>"null"</span>;

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkObjectIsArray(Object aArray){
    <span class='keyword'>if</span> ( ! aArray.getClass().isArray() ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Object is not an array."</span>);
    }
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>boolean</span> isNonNullArray(Object aItem){
    <span class='keyword'>return</span> aItem != <span class='keyword'>null</span> &amp;&amp; aItem.getClass().isArray();
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>boolean</span> isLastItem(<span class='keyword'>int</span> aIdx, <span class='keyword'>int</span> aLength){
    <span class='keyword'>return</span> (aIdx == aLength - <span class='literal'>1</span>);
  }

  <span class='comment'>/**
  * Test harness.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... args) {

    <span class='keyword'>boolean</span>[] booleans = { <span class='keyword'>true</span>, <span class='keyword'>false</span>, <span class='keyword'>false</span> };
    <span class='keyword'>char</span>[] chars = {<span class='literal'>'B'</span>, <span class='literal'>'P'</span>, <span class='literal'>'H'</span>};
    <span class='keyword'>byte</span>[] bytes = {<span class='literal'>3</span>};
    <span class='keyword'>short</span>[] shorts = {<span class='literal'>5</span>,<span class='literal'>6</span>};
    <span class='keyword'>int</span>[] ints = {<span class='literal'>7</span>,<span class='literal'>8</span>,<span class='literal'>9</span>,<span class='literal'>10</span>};
    <span class='keyword'>long</span>[] longs = {<span class='literal'>100</span>,<span class='literal'>101</span>,<span class='literal'>102</span>};
    <span class='keyword'>float</span>[] floats = { <span class='literal'>99.9f</span>, <span class='literal'>63.2f</span>};
    <span class='keyword'>double</span>[] doubles = { <span class='literal'>212.2</span>, <span class='literal'>16.236</span>, <span class='literal'>42.2</span>};
    String[] strings = {<span class='literal'>"blah"</span>, <span class='literal'>"blah"</span>, <span class='literal'>"blah"</span>};
    java.util.Date[] dates = { <span class='keyword'>new</span> java.util.Date(), <span class='keyword'>new</span> java.util.Date() };
    System.out.println(<span class='literal'>"booleans: "</span> + get(booleans));
    System.out.println(<span class='literal'>"chars: "</span> + get(chars));
    System.out.println(<span class='literal'>"bytes: "</span> + get(bytes));
    System.out.println(<span class='literal'>"shorts: "</span> + get(shorts));
    System.out.println(<span class='literal'>"ints: "</span> + get(ints));
    System.out.println(<span class='literal'>"longs: "</span> + get(longs));
    System.out.println(<span class='literal'>"floats: "</span> + get(floats));
    System.out.println(<span class='literal'>"double: "</span> + get(doubles));
    System.out.println(<span class='literal'>"strings: "</span> + get(strings));
    System.out.println(<span class='literal'>"dates: "</span> + get(dates));

    <span class='keyword'>int</span>[] nullInts = <span class='keyword'>null</span>;
    <span class='keyword'>int</span>[] emptyInts = {};
    String[] emptyStrings = {<span class='literal'>""</span>, <span class='literal'>""</span>};
    String[] nullStrings = {<span class='keyword'>null</span>, <span class='keyword'>null</span>};
    System.out.println(<span class='literal'>"null ints: "</span> + get(nullInts));
    System.out.println(<span class='literal'>"empty ints: "</span> + get(emptyInts));
    System.out.println(<span class='literal'>"empty Strings: "</span> + get(emptyStrings));
    System.out.println(<span class='literal'>"null Strings: "</span> + get(nullStrings));

    String[] arrayA = {<span class='literal'>"A"</span>, <span class='literal'>"a"</span>};
    String[] arrayB = {<span class='literal'>"B"</span>, <span class='literal'>"b"</span>};
    String[][] arrayOfArrays = {arrayA, arrayB};
    System.out.println(<span class='literal'>"array Of Arrays: "</span> + get(arrayOfArrays));
  }
} 
</PRE>
<br>
<br>An example run of this class :
<p><tt>>java -cp . myapp.business.ArrayToString</tt>
<br><tt>booleans: [true, false, false]</tt>
<br><tt>chars: [B, P, H]</tt>
<br><tt>bytes: [3]</tt>
<br><tt>shorts: [5, 6]</tt>
<br><tt>ints: [7, 8, 9, 10]</tt>
<br><tt>longs: [100, 101, 102]</tt>
<br><tt>floats: [99.9, 63.2]</tt>
<br><tt>double: [212.2, 16.236, 42.2]</tt>
<br><tt>strings: [blah, blah, blah]</tt>
<br><tt>dates: [Wed Jun 18 09:55:08 EDT 2003, Wed Jun 18 09:55:08 EDT 2003]</tt>
<br><tt>null ints: null</tt>
<br><tt>empty ints: []</tt>
<br><tt>empty Strings: [, ]</tt>
<br><tt>null Strings: [null, null]</tt>
<br><tt>array Of Arrays: [[A, a], [B, b]]</tt>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActionc3b3-2.html?Id=55'>Implementing toString</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='131'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=131 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
